package StudyCode.summary.zipfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CreateZipFileFromDirectoryRecursivelyUsingZipOutputStream {
	public static void main(String args[]) {
		String sourceDir = "E:/Copy";
		String zipFile = "zipdemo.zip";

		try {
			FileOutputStream fout = new FileOutputStream(zipFile);
			ZipOutputStream zout = new ZipOutputStream(fout);
			File fileSource = new File(sourceDir);
			addDirectory(zout, fileSource);
			zout.close();
			System.out.println("Zip文件创建成功!");
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private static void addDirectory(ZipOutputStream zout, File fileSource) {
		File[] files = fileSource.listFiles();

		System.out.println("添加目录 " + fileSource.getName());

		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				addDirectory(zout, files[i]);
				continue;
			}
			try {
				System.out.println("添加文件 " + files[i].getName());
				byte[] buffer = new byte[1024];

				FileInputStream fin = new FileInputStream(files[i]);

				zout.putNextEntry(new ZipEntry(files[i].getName()));

				int length;

				while ((length = fin.read(buffer)) > 0) {
					zout.write(buffer, 0, length);
				}

				zout.closeEntry();

				fin.close();

			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}
}
